from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from django.db.models import Q
from datetime import datetime, timedelta
from .models import DailyWorkProject, DailyWorkItem
from .serializers import (
    DailyWorkProjectSerializer, 
    DailyWorkPlanBulkSerializer
)
from .dingtalk_utils import push_work_plan_to_dingtalk

class DailyWorkPlanViewSet(viewsets.ModelViewSet):
    """
    日工作计划视图集
    """
    queryset = DailyWorkProject.objects.all().prefetch_related('work_items')
    serializer_class = DailyWorkProjectSerializer
    
    def get_serializer_class(self):
        """
        根据动作选择序列化器
        """
        if self.action == 'bulk_save':
            return DailyWorkPlanBulkSerializer
        return DailyWorkProjectSerializer
    
    def get_queryset(self):
        """
        根据查询参数过滤数据
        """
        queryset = DailyWorkProject.objects.all().prefetch_related('work_items')
        
        # 按日期过滤
        date = self.request.query_params.get('date', None)
        if date:
            queryset = queryset.filter(date=date)
        
        # 按日期范围过滤
        start_date = self.request.query_params.get('start_date', None)
        end_date = self.request.query_params.get('end_date', None)
        if start_date and end_date:
            queryset = queryset.filter(date__range=[start_date, end_date])
        elif start_date:
            queryset = queryset.filter(date__gte=start_date)
        elif end_date:
            queryset = queryset.filter(date__lte=end_date)
        
        # 按实验类型过滤
        experiment_type = self.request.query_params.get('experiment_type', None)
        if experiment_type:
            queryset = queryset.filter(experiment_type=experiment_type)
        
        return queryset.order_by('date', 'experiment_type')
    
    @action(detail=False, methods=['post'])
    def bulk_save(self, request):
        """
        批量保存工作计划
        接收前端发送的项目数据结构并保存到数据库
        """
        try:
            # 使用序列化器处理数据
            serializer = DailyWorkPlanBulkSerializer(data=request.data)
            if serializer.is_valid():
                projects = serializer.save()
                return Response(
                    {
                        'message': f'成功保存 {len(projects)} 个项目',
                        'projects': DailyWorkProjectSerializer(projects, many=True).data
                    },
                    status=status.HTTP_201_CREATED
                )
            else:
                return Response(
                    {'errors': serializer.errors},
                    status=status.HTTP_400_BAD_REQUEST
                )
        except Exception as e:
            return Response(
                {'error': f'保存失败: {str(e)}'},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )
    
    @action(detail=False, methods=['get'])
    def get_by_date_range(self, request):
        """
        按日期范围获取工作计划项目
        返回项目列表数据结构
        """
        start_date = request.query_params.get('start_date')
        end_date = request.query_params.get('end_date')
        
        if not start_date or not end_date:
            return Response(
                {'error': '请提供start_date和end_date参数'},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        try:
            # 验证日期格式
            start_date_obj = datetime.strptime(start_date, '%Y-%m-%d').date()
            end_date_obj = datetime.strptime(end_date, '%Y-%m-%d').date()
            
            # 查询数据
            projects = DailyWorkProject.objects.filter(
                date__range=[start_date_obj, end_date_obj]
            ).prefetch_related('work_items').order_by('date', 'experiment_type', 'order')
            
            # 使用序列化器返回数据
            serializer = DailyWorkProjectSerializer(projects, many=True)
            return Response(serializer.data, status=status.HTTP_200_OK)
            
        except ValueError as e:
            return Response(
                {'error': f'日期格式错误: {str(e)}'},
                status=status.HTTP_400_BAD_REQUEST
            )
        except Exception as e:
            return Response(
                {'error': f'查询失败: {str(e)}'},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )
    
    @action(detail=False, methods=['post'])
    def push_to_dingtalk(self, request):
        """
        推送工作计划到钉钉群
        接收前端发送的工作计划数据并推送到钉钉
        """
        try:
            data = request.data
            
            # 验证必要字段
            if not data.get('experiment_type'):
                return Response(
                    {'error': '缺少experiment_type字段'},
                    status=status.HTTP_400_BAD_REQUEST
                )
            
            if not data.get('date'):
                return Response(
                    {'error': '缺少date字段'},
                    status=status.HTTP_400_BAD_REQUEST
                )
            
            if not data.get('projects'):
                return Response(
                    {'error': '缺少projects字段或项目列表为空'},
                    status=status.HTTP_400_BAD_REQUEST
                )
            
            # 调用钉钉推送函数
            result = push_work_plan_to_dingtalk(data)
            
            if result.get('success'):
                return Response(
                    {
                        'message': '推送成功',
                        'detail': result.get('message', '')
                    },
                    status=status.HTTP_200_OK
                )
            else:
                return Response(
                    {
                        'error': '推送失败',
                        'detail': result.get('message', '未知错误')
                    },
                    status=status.HTTP_500_INTERNAL_SERVER_ERROR
                )
                
        except Exception as e:
            return Response(
                {'error': f'推送失败: {str(e)}'},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )
    
    @action(detail=False, methods=['get'])
    def get_recent_plans(self, request):
        """
        获取昨天和今天的工作计划项目
        """
        try:
            # 获取昨天和今天的日期范围
            today = datetime.now().date()
            yesterday = today - timedelta(days=1)
            
            # 查询数据
            projects = DailyWorkProject.objects.filter(
                date__range=[yesterday, today]
            ).prefetch_related('work_items').order_by('date', 'experiment_type', 'order')
            
            # 使用序列化器返回数据
            serializer = DailyWorkProjectSerializer(projects, many=True)
            return Response(serializer.data, status=status.HTTP_200_OK)
            
        except Exception as e:
            return Response(
                {'error': f'查询失败: {str(e)}'},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )
